const express = require("express");
const { v4: cid } = require("uuid");

const app = express();

app.use(express.static("./public"));
app.use(express.json()); //解析 json
app.use(express.urlencoded({ extended: false })); //解析 urlencoded

const users = [
  {
    id: cid(),
    name: "jack",
    age: "20",
    gender: "1",
  },
  {
    id: cid(),
    name: "jack",
    age: "21",
    gender: "1",
  },
  {
    id: cid(),
    name: "rose",
    age: "21",
    gender: "2",
  },
  {
    id: cid(),
    name: "lucy",
    age: "22",
    gender: 2,
  },
];

// query,read
app.get("/users", (req, res) => {
  let data = [];
  if (req.query.name) {
    data = users.filter((el) => el.name === req.query.name);
  }
  if (req.query.age) {
    data = data.filter((el) => el.age === req.query.age);
  }
  if (Object.keys(req.query).length === 0) {
    res.send(users);
  } else {
    res.send(data);
  }
});

// 添加
app.post("/users", (req, res) => {
  const data = {
    id: cid(),
    ...req.body,
  };
  users.push(data);
  res.send(data);
});

app.delete("/users/:id", (req, res) => {
  const index = users.findIndex((el) => el.id === req.params.id);
  if (index) {
    users.splice(index, 1);
  }
  res.status(204);
  res.send(null);
});

app.patch("/users/:id", (req, res) => {
  const index = users.findIndex((el) => el.id === req.params.id);
  const data = {
    ...users[index],
    ...req.body,
  };
  users[index] = data;
  res.send(data);
});

app.listen(3000, () => {
  console.log("success", "http://127.0.0.1:3000");
});
